from django.contrib.auth.models import User
from rest_framework import serializers

from snippets.models import LANGUAGE_CHOICES, STYLE_CHOICES, Snippet

from .models import Snippet


class SnippetSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)  # 序列化时只读字段
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)  # 标题字段，可选，允许空白，最大长度100
    code = serializers.CharField(style={'base_template': 'textarea.html'})  # 代码内容字段，指定显示样式为文本域
    linenos = serializers.BooleanField(required=False)  # 是否显示行号字段，可选
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
                                       default='python')  # 语言选择字段，选项从 LANGUAGE_CHOICES 中获取，默认为 python
    style = serializers.ChoiceField(choices=STYLE_CHOICES,
                                    default='friendly')  # 代码风格选择字段，选项从 STYLE_CHOICES 中获取，默认为 friendly
    owner = serializers.ReadOnlyField(source='owner.username')
    def create(self, validated_data):
        """
        创建并返回一个新的 `Snippet` 实例，给定验证过的数据。
        """
        return Snippet.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
              更新并返回一个已存在的 `Snippet` 实例，给定验证过的数据。
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance


class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = ['id', 'username', 'snippets']